<template>
  <div :class="{'mobile-create': showMobilePage}" class="with-draw-form">
    <div class="pay-application-title">
      <Title title="结算单基本信息" />
    </div>
    <BaseInfo
      ref="notOrderModuleRef"
      v-model="headForm"
      :is-not-order="isNotOrder"
      :cost-belong="costBelong"
      :is-edit="!!(isEdit || isLaunchExamine)"
      :step-one-data="stepOneData"
      :is-draft="Boolean(stepThreeData.isDraft)"
      :is-invite="isInvite"
      @supplierChangeMethod="supplierChangeMethod"
    />
    <div v-if="!isNotOrder" class="pay-application-tab-list">
      <div :class="{'active': activeTab === 0}" class="tab-item" @click="activeTab = 0">审批单信息</div>
      <div :class="{'active': activeTab === 1}" class="tab-item" @click="activeTab = 1">结算单信息</div>
    </div>
    <!-- 所选择的订单或成本列表 -->
    <div v-show="activeTab === 0">
      <div class="pay-application-title">
        <Title title="结算信息" />
        <div>
          <span class="title-tip">可引用历史发起的审批填写内容👉</span>
          <el-button type="primary" size="small" class="btn-hover" @click="openHistoryDrawer">引用历史表单数据</el-button>
        </div>
      </div>
      <el-form
        ref="data-form-ref"
        :rules="headRules"
        :model="headForm"
        :label-position="showMobilePage?'left':'right'"
        label-width="100px"
        class="lineHeight32">
        <el-row type="flex" class="response-el-row">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="settleName" label="结算名称" >
              <el-input v-model="headForm.settleName" :disabled="settleNameDisabled || exitFinish" class="width240" size="small" maxlength="30" placeholder="不超过30字符" />
            </el-form-item>
          </el-col>
          <el-col v-if="isNotOrder" :span="12" class="responsive-col-lg-8">
            <el-form-item prop="settleAmountTotal" label="结算总金额" >
              <el-input
                v-model="headForm.settleAmountTotal"
                :disabled="disabledSettleAmount"
                class="width240"
                size="small"
                oninput="if(value>99999999999)value=99999999999;if(value<0)value=0"
                type="number"
                placeholder="请填写金额"
                @change="numberInputChange()" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :prop="'accountType'" label="账户类型" >
              <selectWithoutHttp
                v-model="headForm.accountType"
                :list-data="accountTypeOption"
                class="width240"
                placeholder="请选择"
                key-name="value"
                label-name="label"
                @change="accountTypeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="付款类型" prop="requestFundsType" >
              <selectWithoutHttp v-model="headForm.requestFundsType" :list-data="requestFundsOptions" class="width240" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="proposer" label="申请人" >
              <selectWithUserLoad
                v-model="headForm.proposerUserObj"
                :default-list="headForm.proposerUserObj.id?[headForm.proposerUserObj]:[]"
                :show-check-user="true"
                class="width240"
                value-type="object"
                filterable
                key-name="id"
                label-name="userName"
                clearable
                @clear="clear"
                @changeMethod="changeMethod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="申请人部门" prop="proposerDepartment" >
              <el-cascader
                v-model="headForm.proposerDepartment"
                :show-all-levels="false"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                filterable
                class="width240"
                size="small"
                clearable
              >
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="所属公司" prop="ourTitle">
              <el-select v-model="headForm.ourTitle" placeholder="请选择" clearable filterable class="width240" size="small" popper-class="panel-auto-width">
                <el-option
                  v-for="item in companies"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="款项归属" prop="paymentBelong" >
              <el-cascader
                v-model="headForm.paymentBelong"
                :show-all-levels="false"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                filterable
                class="width240"
                placeholder="请选择款项归属"
                size="small"
                clearable
              >
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="isAllocation" label="分摊费用" >
              <el-radio-group v-model="headForm.isAllocation">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="contractSign" label="合同签订" >
              <el-radio-group v-model="headForm.contractSign" @change="contractSignChange">
                <el-radio :label="0">已签订</el-radio>
                <el-radio :label="1">未签订</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="标签" prop="tag" class="client-name">
              <TagSelect v-model="headForm.tag" :collapse-tags="false" :module-type="TAG_MODULES.PROCESS" class="width240" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="confirmType" label="达人结算确认" >
              <el-radio-group v-model="headForm.confirmType">
                <el-radio :label="-1">无</el-radio>
                <el-radio :label="0">邮箱</el-radio>
                <el-radio :label="1">达人审批</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="attachment" label="附件" >
              <upAttachment
                :hide-confirm="true"
                :file-list="headForm.attachment"
                import-api="/common/file/upload"
                btn-text="上传附件"
                @complateSetData="complateSetData($event)"
                @removeFileList="removeFileList($event)"
              />
            </el-form-item>
          </el-col>
          <template v-if="[2, 3].includes(headForm.accountType)">
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item prop="invoice" label="发票" >
                <selectWithoutHttp
                  v-model="headForm.invoice"
                  :list-data="invoiceOption"
                  class="width240"
                  key-name="id"
                  label-name="value"
                  @change="invoiceChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item prop="planTime" label="预计取得时间" >
                <el-date-picker
                  v-model="headForm.planTime"
                  class="width240"
                  type="date"
                  size="small"
                  value-format="timestamp"
                  format="yyyy/MM/dd"
                  placeholder="选择日期" />
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="remark" label="备注" >
              <el-input v-model="headForm.remark" class="width240" size="small" maxlength="500" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="remarkWithInside" label="对内备注" >
              <el-input v-model="headForm.remarkWithInside" class="width240" size="small" maxlength="200" placeholder="备注内容审批完成后自动删除" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item prop="temporaryAttachment" label="临时附件" >
              <upAttachment
                :hide-confirm="true"
                :file-list="headForm.temporaryAttachment"
                import-api="/common/file/upload"
                btn-text="上传附件"
                @complateSetData="complateSetData($event,'temporaryAttachment')"
                @removeFileList="removeFileList($event,'temporaryAttachment')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 发票列表 -->
      <invoiceList
        v-if="[2, 3].includes(headForm.accountType) && headForm.invoice === 0"
        ref="involeListRef"
        v-model="headForm.invoiceList"
        :is-edit="true"
        @onRowDel="delInvoiceRow"
        @attachmentAdd="attachmentAdd"
      />
      <!-- 收款账户 -->
      <collectAccountComponent
        v-if="[2, 3].includes(headForm.accountType)"
        ref="collectAccountComponentRef"
        v-model="headForm.collectAccount"
        :is-edit="true"
        :account-type="headForm.accountType"
        :is-commerce="Number(headForm.supplierSource) === 6"
        :supplier-id="headForm.channelId || supplierId || 0"
        :cost-belong="costBelong"
      />
      <!-- 关联合同 -->
      <relatedContractTable
        v-if="headForm.contractSign === 0"
        ref="relatedContractTable"
        :is-edit="true"
        :list-setting="listSetting"
        v-model="headForm.contractList"
        :style="[2, 3].includes(headForm.accountType) || ([2, 3].includes(headForm.accountType) && headForm.invoice === 0) ? {marginTop: '30px'}: {marginTop: '10px'}"
        @addRow="addContractRow"
        @selectContract="openSelectContract"
        @selectChange="selectChange"
        @scrollSelectChange="scrollSelectChange"
      />
      <collectMonenyList
        ref="collectMonenyListRef"
        :total-price="totalPrice"
        v-model="headForm.collectMoneyData.list"
        :account-type="headForm.accountType"
        :request-funds-type="headForm.requestFundsType"
        :step-one-data="stepOneData"
        :is-edit="true"
        :is-commerce="Number(headForm.supplierSource) === 6"
        :settle-id="settleId"
        :is-select-order="isSelectOrder"
        :is-not-order="isNotOrder"
        :supplier-id="headForm.channelId || supplierId || 0"
        :select-cost="stepThreeData.selectCost"
        :cost-belong="costBelong"
        :margin-top="headForm.contractSign"
        style="margin-bottom:32px;"
        font-size="16px"
        @setSupplierRate="setSupplierRate" />
      <!-- 分摊费用 -->
      <AllocationAmount v-if="headForm.isAllocation" ref="AllocationAmountRef" v-model="headForm.allocationList" is-edit/>
      <!-- 关联合同弹窗 -->
      <relatedContract
        ref="showRelatedContract"
        :has-contract-code="true"
        :is-show-other="true"
        :visible.sync="showRelatedContract"
        exit-snapshot
        @confirmRelatedContract="confirmRelatedContract"
      />
    </div>
    <settlementOrderInfo
      v-if="!isNotOrder && (!isAccountSettle || isAccountSettle && stepThreeData.selectCost)"
      v-show="activeTab === 1"
      :step-three-data="stepThreeData"
      :step-one-data="stepOneData"
      :settle-id="settleId" />
  </div>
</template>

<script>
// api
import { deptList } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { getSupplierDetail, currentWidthdrawInfo, supplierInfo } from '@/api/supplier';
import { getUserList } from '@/api/user';
import { getSignUpOtherOptions } from '@/api/legal';

// components
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import upAttachment from '@/components/Common/upAttachment/index';
import invoiceList from '@/components/SupplierComponent/invoiceList/invoiceList';
import collectMonenyList from '@/components/SupplierComponent/colletMoneyList/colletMoneyList';
import collectAccountComponent from '@/components/SupplierComponent/colletMoneyList/collectAccount';
import relatedContract from '@/components/CreateOrder/relatedContract';
import AllocationAmount from '@/components/SupplierComponent/AllocationAmount/index';
import BaseInfo from './BaseInfo';
import TagSelect from '@/components/Common/tagSelect';
import relatedContractTable from '@/components/SupplierComponent/relatedContractTable';
import Title from '@/components/Title';
import settlementOrderInfo from './settlementOrderInfo.vue';
// utils
import { mapState } from 'vuex';
import { TAG_MODULES } from '@/utils/const';
import { encryption } from '@/utils';
import math from '@/utils/math';
import { getFirstDepartment } from '@/utils/index';

export default {
  components: {
    selectWithUserLoad, selectWithoutHttp, upAttachment,
    invoiceList, collectMonenyList, relatedContract, AllocationAmount,
    BaseInfo, TagSelect, collectAccountComponent, relatedContractTable,
    settlementOrderInfo, Title
  },
  inject: {
    setSettleId: { default: null }
  },
  props: {
    settleId: {
      type: Number | String,
      default: null
    },
    stepOneData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    stepThreeData: {
      type: Object,
      default: () => {
        return null;
      }
    },
    totalPrice: { // 第二步中所选择订单的结算总金额，单位为分
      type: Number,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isNotOrder: { // 是否为其他付款结算(非订单)
      type: Boolean,
      default: false
    },
    showDraft: {
      type: Boolean | Number,
      default: false
    },
    isLaunchExamine: { // 在同一个结算单上发起一个新的审批单
      type: Boolean | Number,
      default: false
    }

  },
  data() {
    return {
      TAG_MODULES,
      showRelatedContract: false,
      isCustomContract: false,
      invoiceOption: [
        { id: 0, value: '已取得' }, { id: 1, value: '未取得' }, { id: 2, value: '无需发票' },
        { id: 3, value: '财务统一申请' }, { id: 4, value: '业务统一申请' }
      ],
      accountTypeOption: [{ value: 1, label: '第三方账户' }, { value: 2, label: '对公银行账户' }, { value: 3, label: '对公其他账户' }],
      headForm: {
        accountType: 1, // 类型 1: 第三方账户 2: 对公账户
        settleName: '',
        collectMoneyData: { // 收款人列表
          // 当选择付款类型为全款，禁用达人到手金额和实付金额
          list: [
            { collectMoneyType: 0, priceRate: this.priceRate,
              _disabledObj: { actualAmount: true, withdrawAmount: true }
            }
          ]
        },
        collectAccount: { // 收款账户
          payName: '',
          payNum: '',
          bank: '',
          province: '',
          subBank: ''
        },
        invoiceList: [{}], // 发票列表
        allocationList: [{}],
        remark: '', // 备注
        remarkWithInside: '', // 对内备注
        attachment: [], // 附件
        contractSign: 0, // 合同签订
        proposer: '', // 申请人id
        proposerName: '', // 申请人id
        proposerDepartment: '', // 申请人部门id
        proposerUserObj: '', // id userName
        // 对公账户独有
        invoice: '',
        planTime: null,
        requestFundsType: 0, // 【v2.9.6】付款类型
        isAllocation: 0, // 【v3.0.4】分摊费用
        paymentBelong: '',
        contractNum: '', // 自定义输入合同编号 与contractList互斥
        contractList: [], // 选择系统内的合同编号 与contractNum互斥
        channelId: '', // 【v3.0.4】供应商id 其他付款结算(非订单)
        channelName: '', // 【v3.0.4】供应商名称 其他付款结算(非订单)
        supplierSource: 0, // 【v3.0.4】供应商来源 其他付款结算(非订单)使用 0:销售供应商  2:萌力供应商  6有赞供应商其他付款结算(非订单)
        ourTitle: '', // 所属公司
        temporaryAttachment: [], // 【3.0.9.1】临时附件
        confirmType: -1, // 【3.3.0】达人结算确认
        settleAmountTotal: ''
      },
      deptOption: [], // 部门列表
      deptTreeList: [],
      companies: [], // 所属公司列表
      requestFundsOptions: [{ id: 0, value: '账号付款' }, { id: 1, value: '其他付款' }],
      activeTab: 0, // 0:本次审批单信息 1:结算单信息
      delInvoiceList: [], // 被删除的发票列表
      settleNameDisabled: false, // 结算名称是否禁止输入
      supplierRate: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    exitFinish() {
      return Number(this.$route.query.exitFinish) === 1;
    },
    costBelong() { // 成本归属 0:销售成本 2:萌力成本 6:有赞成本
      if (this.stepOneData) {
        return this.stepOneData.costBelong;
      }
      return undefined;
    },
    supplierId() { // 供应商id
      if (this.stepOneData) {
        return this.stepOneData.supplierId;
      }
      return undefined;
    },
    // 审批单列表中是否存在已完成，
    disabledSettleAmount() {
      return !!this.$route.query.disabledSettleAmount;
    },
    headRules() {
      const validateSelect = (msg) => {
        return (ruleItem, value, callback) => {
          const proposerUserObj = this.headForm.proposerUserObj;
          if (!proposerUserObj || !proposerUserObj.id) { callback(new Error(msg)); } else { callback(); }
        };
      };
      const validateWriteOffLoan = (msg, key) => {
        return (ruleItem, value, callback) => {
          const data = this.headForm[key];
          if (data || data === false || data === 0) { callback(); } else { callback(new Error(msg)); }
        };
      };
      const validateContractSign = () => {
        return (ruleItem, value, callback) => {
          let contract;
          if (this.isCustomContract) {
            contract = this.headForm.contractNum; // 自己输入的合同编号
          } else {
            contract = this.headForm.contractList;
          }
          if (!contract || contract.length === 0) {
            callback(new Error(this.isCustomContract ? '请输入合同编号' : '请选择合同'));
          } else {
            callback();
          }
        };
      };
      const contractSign = this.headForm.contractSign;
      const rule = {
        accountType: { required: true, message: '请选择', trigger: 'change' },
        proposer: { required: true, validator: validateSelect('请选择申请人'), trigger: 'change' },
        proposerDepartment: { required: true, message: '请选择申请人部门', trigger: 'change' },
        ourTitle: { required: true, message: '请选择所属公司', trigger: 'change' },
        paymentBelong: { required: true, message: '请选择款项归属', trigger: 'change' },
        settleName: { required: true, message: '请输入结算名称', trigger: 'blur' },
        isAllocation: { required: true, validator: validateWriteOffLoan('请选择分摊费用', 'isAllocation'), trigger: 'change' },
        requestFundsType: { required: true, validator: validateWriteOffLoan('请选择付款类型', 'requestFundsType'), trigger: 'change' }
      };
      if (contractSign === 0) {
        rule.contractNum = { required: true, validator: validateContractSign(), trigger: 'change' };
      } else {
        delete rule.contractNum;
      }
      if (this.isNotOrder) {
        rule['settleAmountTotal'] = {
          required: true, message: '请输入结算总金额', trigger: 'blur'
        };
      }
      return rule;
    },
    isInvite() {
      return this.stepOneData.isInvite;
    },
    inviteUrl() {
      const inviteCode = encryption(this.settleId);
      return `${location.origin}/#/businessPage/supplierDetail?settleId=${this.settleId}&id=${this.supplierId}&isSettle=true&isInvite=${inviteCode}`;
    },
    listSetting() {
      return [
        { label: '项目名称', width: '240px', type: 'inputText', isRequired: true, keyword: 'projectName', maxlength: 16 },
        { label: '合同编号', type: 'inputText', width: '200px', isRequired: true, keyword: 'contractNum', maxlength: 50 },
        { label: '合同类型', type: 'select', isRequired: true, width: '180px', keyword: 'contractType', options: [
          { id: 2, name: '推广销售类' },
          { id: 3, name: '渠道采买类' },
          { id: 4, name: 'IP商业授权类' },
          { id: 1, name: '一般购销/委托服务类' },
          { id: 5, name: '合同/kol/直播类' },
          { id: 6, name: '机构/平台合作类' },
          { id: 7, name: '电商产品购销类' },
          { id: 8, name: '投资类' },
          { id: 9, name: '其他类' }
        ] },
        {
          label: '签约对方',
          type: 'scrollSelect',
          width: '150px',
          keyword: 'oppCompanyData',
          valueType: 'object',
          isRequired: false,
          keyName: 'uuid',
          labelName: 'name',
          renderKeyword: 'name',
          loadmoreMethod: this.getSelectOtions()
        },
        { label: '申请人', type: 'scrollSelect', keyName: 'id', labelName: 'userName', renderKeyword: 'userName', isRequired: true, keyword: 'proposerName', loadmoreMethod: getUserList, notShowClear: true },
        { label: '申请人部门', type: 'cascader', width: '150px', keyword: 'proposerDepartment', showAllLevels: false, emitPath: false, checkStrictly: true, isRequired: true, keyName: 'id', labelName: 'name', options: this.deptTreeList, notShowClear: true }
      ];
    },
    isSelectOrder() {
      // 用于隐藏或显示一键填单，选择成本时，没有一键填单
      if (this.isNotOrder) return false;
      const stepThreeData = this.stepThreeData;
      let res = false;
      if (Object.hasOwnProperty.call(stepThreeData, 'closeAccountOrderNumber')) {
        res = stepThreeData.closeAccountOrderNumber > 0;
      } else if (stepThreeData.selectCost && stepThreeData.selectCost.length) {
        stepThreeData.selectCost.forEach(i => {
          if ((i.orderList && i.orderList.length) || (i.orderIds && i.orderIds.length)) {
            res = true;
          }
        });
      }
      return res;
    },
    isAccountSettle() { // 待办中心结算
      return !!this.$route.query.isAccountSettle;
    },
    priceRate() {
      return this.supplierRate || 1.065;
    }
  },
  created() {
    this.init();
    if (this.$route.query.isAccountSettle) {
      this.accountSettleInfo();
    }
    this.getSupplierInfo();
    if (!this.isEdit && !this.isNotOrder) {
      // 如果是第一次发起，则把第二步的所选择订单的结算总金额，填入到默认列中
      this.initCollectMoney();
      this.headForm.supplierSource = this.stepOneData.costBelong;
    }
    if (this.$route.query.completeStatus) {
      this.settleNameDisabled = true;
    }
  },
  mounted() {
    const { hasRate, supplierPriceRate } = this.stepOneData;
    if (hasRate && this.headForm.accountType === 1 && this.headForm.collectMoneyData.list) {
      this.$set(this.headForm.collectMoneyData.list[0], 'priceRate', supplierPriceRate);
    }
  },
  methods: {
    init() {
      this.getDeptList();
      this.queryDeptTreeList();
      this.queryOurTitleList();
      this.iniProposer();
      // 成本来源=渠道订单、项目渠道单，默认选中账号付款；
      // 成本来源=项目订单、商务订单单、营销授权单；默认选中其他付款
      if (this.costBelong === 0 || this.costBelong === 5) {
        this.headForm.requestFundsType = 0;
      } else {
        this.headForm.requestFundsType = 1;
      }
      if (this.isNotOrder) this.headForm.requestFundsType = 1;
      if (this.isNotOrder && !this.isEdit) {
        const pageFrom = this.$route.query.from || 'saleSupplier';
        const sourceMap = {// 0飞博供应商 2萌力供应商 6有赞供应商
          'saleSupplier': 0,
          'mengliSupplier': 2,
          'commerceSupplier': 6
        };
        this.headForm.supplierSource = sourceMap[pageFrom];
      }
      setTimeout(() => {
        this.$refs['data-form-ref'].clearValidate();
      }, 0);
    },
    setSupplierRate(priceRate) {
      this.supplierRate = priceRate;
    },
    getSelectOtions() {
      return function(params) {
        return new Promise((resolve, reject) => {
          getSignUpOtherOptions(params).then(res => {
            res.data && res.data.items && res.data.items.forEach(i => {
              i.uuid = i.id + '-' + i.type;
            });
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
    },
    // 待办，账号结算获取信息进行填充
    accountSettleInfo() {
      let data = localStorage.getItem('accountSettleData');
      if (data && !['null', 'undefined'].includes(data)) {
        data = JSON.parse(data);
        // 回填settleId
        if (this.setSettleId) {
          this.setSettleId({
            settleId: data.id,
            supplierId: data.channelId,
            costBelong: data.supplierSource
          });
        }
        this.$emit('setIsSaveCollectMoneyData', data.isSaveCollectMoneyData);
        if (data.collectMoneyData.list.length) {
          data.collectMoneyData.list.forEach(it => {
            it.actualAmount = (it.actualAmount / 100).toFixed(2);
            it.settlementAmount = (it.settlementAmount / 100).toFixed(2);
            it.withdrawAmount = (it.withdrawAmount / 100).toFixed(2);
          });
        }
        if (data.contractList && data.contractList.length) {
          data.contractList.forEach(it => {
            it.username = it.proposerName;
            data.contractList.forEach(it => {
              if (data.contractSign === 0 && it.contractSourceType === 1) {
                it.disable = true;
              }
              it.oppCompanyData = it.oppCompany ? { name: it.oppCompany, id: it.oppCompanyId, type: it.oppCompanyType } : null;
            });
          });
        }
        if (!data.allocationList) {
          data.allocationList = [{}];
        }
        if (!data.collectAccount) {
          data.collectAccount = {
            payName: '',
            payNum: '',
            bank: '',
            province: '',
            subBank: ''
          };
        } else {
          for (const key in data.collectAccount) {
            if (key === 'province' && data.collectAccount[key]) {
              data.collectAccount[key] = data.collectAccount[key].replace(/-/, ',');
            }
            if (!data.collectAccount[key]) { data.collectAccount[key] = ''; }
          }
        }
        this.headForm = data;
        this.headForm.contractList = data.contractList || [];
        this.headForm.invoiceList = [];
        const proposerUserObj = {
          id: data.proposer || this.userInfo.id,
          userName: data.proposerName || this.userInfo.userName,
          avatar: data.proposerAvatar || this.userInfo.avatar
        };
        this.$set(this.headForm, 'proposerUserObj', proposerUserObj);
        this.$set(this.headForm, 'proposer', data.proposer || this.userInfo.id);
        this.$set(this.headForm, 'proposerName', data.proposerName || this.userInfo.userName);
      }
    },
    clear() {
      this.$set(this.headForm, 'proposerUserObj', '');
      this.$set(this.headForm, 'proposer', '');
      this.$set(this.headForm, 'proposerName', '');
      this.$forceUpdate();
    },
    resetForm() {
      this.headForm.channelId = '';
      this.$refs['data-form-ref'].resetFields();
      this.$refs['notOrderModuleRef'].clearValidate();
      this.headForm.contractList = [];
      this.headForm.invoiceList = [];
      this.clearCollectMoneyData();
    },
    iniProposer() {
      if (!this.headForm.proposer) {
        this.headForm.proposerUserObj = {
          id: this.userInfo.id,
          userName: this.userInfo.userName,
          post: this.userInfo.post,
          avatar: this.userInfo.avatar
        };
        this.headForm.proposer = this.userInfo.id;
        this.headForm.proposerName = this.userInfo.userName;
        // 申请人部门
        if (this.userInfo.deptName && this.userInfo.deptName.length) {
          this.headForm.proposerDepartment = this.userInfo.deptName[0].id;
          this.headForm.paymentBelong = this.userInfo.deptName[0].id;
        }
      }
    },
    changeProposer() {
      this.iniProposer();
      this.$emit('changeProposer', this.headForm.proposerUserObj);
    },
    supplierChangeMethod(data) {
      if (data.hasRate && this.headForm.collectMoneyData.list && this.headForm.accountType === 1) {
        this.headForm.collectMoneyData.list.forEach(i => {
          this.$set(i, 'priceRate', data.priceRate);
          this.$refs['collectMonenyListRef'].changeInputNumberData({ item: i, key: 'priceRate' });
        });
      }
      this.$emit('supplierChangeMethod', data);
    },
    // 我方抬头/所属公司
    queryOurTitleList() {
      getIssueOurTitleList({}).then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name
            });
          });
          this.companies = result;
        }
      });
    },
    // 暴露给父组件获取参数
    getParams() {
      const paramsData = _.cloneDeep(this.headForm);
      paramsData.settlementMethod = this.stepOneData.settlementMethod;
      if (paramsData.accountType === 1) {
        paramsData.invoiceList = [];
      }
      if (!paramsData.isAllocation) {
        paramsData.allocationList = [];
      }
      if (paramsData.allocationList && paramsData.allocationList.length > 0) {
        paramsData.allocationList.forEach(i => {
          if (i.amount) i.amount = Number(i.amount);
        });
      }
      if (paramsData.accountType === 1) {
        paramsData.collectAccount = null;
      }
      if (paramsData.invoiceList && paramsData.invoiceList.length > 0) {
        paramsData.invoiceList.forEach(i => {
          if (i.invoicePrice) i.invoicePrice = Number(i.invoicePrice);
          if (i.tax) i.tax = Number(i.tax);
        });
      }
      if (paramsData.collectMoneyData && paramsData.collectMoneyData.list) {
        paramsData.collectMoneyData.list = paramsData.collectMoneyData.list.map(item => {
          item.settlementAmount = item.settlementAmount || item.settlementAmount === 0 ? (Number(item.settlementAmount) * 100).toFixed(0) : item.settlementAmount;
          item.withdrawAmount = item.withdrawAmount || item.withdrawAmount === 0 ? (Number(item.withdrawAmount) * 100).toFixed(0) : item.withdrawAmount;
          item.actualAmount = item.actualAmount || item.actualAmount === 0 ? (Number(item.actualAmount) * 100).toFixed(0) : item.actualAmount;
          return item;
        });
      }
      if (paramsData.contractList) {
        paramsData.contractList = paramsData.contractList.map(item => {
          item.contractCode = item.contractNum;
          item.contractName = item.projectName;
          if (!item.id && item.oppCompanyData) {
            item.oppCompany = item.oppCompanyData.name || null;
            item.oppCompanyId = item.oppCompanyData.id || null;
            item.oppCompanyType = item.oppCompanyData.type || null;
          }
          return item;
        });
      }

      if (paramsData.settleAmountTotal) {
        paramsData.settleAmountTotal = Number(paramsData.settleAmountTotal);
      }
      return paramsData;
    },
    // 关联合同新增一行
    addContractRow() {
      const { id, userName, departmentAry } = this.userInfo;
      // 申请人、申请部门默认取当前用户的
      const temp = [...this.headForm.contractList];
      temp.push({
        contractName: '',
        contractCode: '',
        contractNum: '',
        projectName: '',
        oppCompanyData: null,
        proposer: id,
        proposerName: userName,
        proposerDepartment: getFirstDepartment(departmentAry),
        proposerDepartmentName: '',
        contractSourceType: 0,
        userName
      });
      const res = temp.filter(it => !it.hasOwnProperty('orderPrivateId'));
      this.$set(this.headForm, 'contractList', res);
    },
    // 表单验证
    geValidate() {
      const involeListRef = this.$refs.involeListRef;
      const arr = [];
      arr.push(this.$refs['data-form-ref']);
      arr.push(this.$refs['collectMonenyListRef']);
      if (this.$refs['relatedContractTable']) arr.push(this.$refs['relatedContractTable']);
      if (this.$refs['collectAccountComponentRef']) arr.push(this.$refs['collectAccountComponentRef']);
      if (this.$refs.notOrderModuleRef) arr.push(this.$refs.notOrderModuleRef);
      if (this.$refs.AllocationAmountRef) arr.push(this.$refs.AllocationAmountRef);
      if (involeListRef) arr.push(involeListRef);
      return arr;
    },
    validateRelateContract() {
      return this.headForm.contractSign === 0 && (!this.headForm.contractList || !this.headForm.contractList.length);
    },
    getIdByName(name) {
      const res = this.deptOption.find(it => it.value === name);
      const result = res && res.id ? res.id : null;
      return result;
    },
    accountTypeChange() {
      if (this.headForm.accountType === 2) {
        this.headForm.collectAccount = {
          payName: '',
          payNum: '',
          bank: '',
          province: '',
          subBank: ''
        };
      } else if (this.headForm.accountType === 3) {
        this.headForm.collectAccount = {
          payPlatform: '',
          payName: '',
          payNum: ''
        };
      } else {
        this.headForm.collectAccount = null;
      }
      this.clearValidate();
    },
    clearValidate() { // 切换账户类型的时候清除表单验证
      this.$refs['data-form-ref'].clearValidate();
      this.headForm.contractSign = 0;
      this.headForm.invoice = 0;
      this.headForm.contractSign = 0;
      this.clearCollectMoneyData();
    },
    // 切换账户类型时清空收款人列表
    clearCollectMoneyData() {
      this.headForm.collectMoneyData.list = [{
        collectMoneyType: 0,
        priceRate: this.priceRate
      }];
    },
    invoiceChange(e) {
      if (e !== 0) {
        this.$set(this.headForm, 'invoiceList', []);
      }
    },
    // 附件上传
    complateSetData({ data, fileName }, key = 'attachment') {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (!this.headForm[`${key}`]) { this.headForm[`${key}`] = []; }
      this.headForm[`${key}`].push(fileList);
    },
    removeFileList({ file, index }, key = 'attachment') {
      this.headForm[`${key}`].splice(index, 1);
    },
    changeMethod(value) {
      this.headForm.proposer = value.id;
      this.headForm.proposerName = value.userName;
      // proposerDepartment
      if (value.deptName && value.deptName.length) {
        this.headForm.proposerDepartment = value.deptName[0].id;
      }
      const proposer = {
        id: value.id,
        avatar: value.avatar,
        userName: value.userName,
        post: value.post
      };
      this.$emit('changeProposer', proposer);
    },
    // 操作
    setSettleName(name) {
      this.headForm.settleName = name;
    },
    initCollectMoney() {
      // 一次结算
      // 如果是第一次发起，则把第二步的所选择订单的结算总金额，填入到默认列中
      if (this.stepOneData.settlementMethod === 1 && this.headForm.collectMoneyData.list.length === 1) {
        const totalPrice = math.divide(this.totalPrice, 100);
        this.$set(this.headForm.collectMoneyData.list[0], 'settlementAmount', totalPrice);
        const item = this.headForm.collectMoneyData.list[0];
        this.$nextTick(() => {
          if (this.$refs.collectMonenyListRef) this.$refs.collectMonenyListRef.changeInputNumberData({ item, key: 'settlementAmount' });
        });
      }
    },
    setSupplier(data) {
      this.headForm.supplierSource = data.supplierSource;
      this.headForm.channelId = data.channelId;
      this.headForm.channelName = data.channelName;
    },
    getDeptList() {
      deptList().then(res => {
        if (res.code === 200) {
          this.deptOption = res.data;
        }
      });
    },
    contractListFormat() {
      if (this.headForm.contractList && this.headForm.contractList.length) {
        const res = this.headForm.contractList.map(it => ({
          ...it,
          creator: it.creator || this.userInfo.userName
          // userName: it.proposer || it.userName
        }));
        this.$set(this.headForm, 'contractList', res);
      }
    },
    // 获取部门
    queryDeptTreeList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        // if (sort) cascaderSoft(this.paramsObj.cooperationDepartment, this.deptTreeList);
      }).then(() => {
        this.contractListFormat();
      }).catch(e => {
        console.log(e);
      });
    },
    contractSignChange() {
      this.$refs['data-form-ref'].clearValidate();
      this.$set(this.headForm, 'contractList', []);
    },
    switchInput() {
      this.isCustomContract = !this.isCustomContract;
      this.$set(this.headForm, 'contractList', []);
      this.$set(this.headForm, 'contractNum', '');
      this.$refs['data-form-ref'].clearValidate();
    },
    deleteContractList(tag, index) {
      this.headForm.contractList.splice(index, 1);
    },
    // 合同关联
    confirmRelatedContract(data) {
      let temp = this.headForm.contractList ? [...this.headForm.contractList] : [];
      // contractSourceType 0: 手动添加 1:关联合同
      if (temp.length) {
      // 手动添加保留，关联合同覆盖
        temp = temp.filter(it => it.contractSourceType === 0);
      }
      data.forEach(it => {
        // 是否来自已经关联的合同
        const isFormPayApplication = it.isFormPayApplication;
        temp.push({
          ...it,
          disable: true,
          contractNum: it.contractCode || it.contractNum,
          projectName: it.contractName || it.projectName,
          contractSourceType: 1,
          userName: isFormPayApplication ? it.userName : it.proposer,
          proposerName: isFormPayApplication ? it.proposerName : it.proposer,
          proposer: isFormPayApplication ? it.proposer : it.proposerId,
          proposerDepartmentName: isFormPayApplication ? it.proposerDepartmentName : it.department,
          proposerDepartment: it.proposerDepartment,
          oppCompanyData: it.oppCompany ? { name: it.oppCompany, id: it.oppCompanyId, type: it.oppCompanyType } : null
        });
      });
      this.$set(this.headForm, 'contractList', temp);
      this.showRelatedContract = false;
      this.$refs['data-form-ref'].validateField('contractNum');
    },
    openSelectContract() {
      this.contractListFormat();
      this.showRelatedContract = true;
      this.$refs['showRelatedContract'].init();
      let result = [];
      if (this.headForm.contractList && this.headForm.contractList.length) {
        result = this.headForm.contractList.filter(it => it.contractSourceType === 1);
      }
      result.forEach(i => {
        i.isFormPayApplication = true;
      });
      this.$refs['showRelatedContract'].initSelectData(result);
    },
    selectChange(data) {
      if (data.key === 'proposerName' && !data.item.proposerName) {
        const index = data.rowIndex;
        this.$set(this.headForm.contractList[index], 'proposerDepartment', '');
      }
    },
    scrollSelectChange(keyword, data, rowIndex) {
      const index = rowIndex;
      if (keyword === 'proposerName') {
        this.$set(this.headForm.contractList[index], 'proposerDepartment', data.departmentAry ? getFirstDepartment(data.departmentAry) : '');
      }
    },
    clearForm() {
      this.headForm.accountType = 1;
      this.headForm.remark = '';
      this.headForm.attachment = [];
      this.headForm.contractSign = 0;
      this.headForm.proposer = '';
      this.headForm.proposerName = '';
      this.headForm.proposerUserObj = '';
      this.headForm.invoice = 0;
      this.headForm.planTime = null;
    },
    delInvoiceRow(val) {
      // isEdit: 从审批记录列表点击修改进入时,需要标记被删除的发票
      if (val.id || (this.isEdit && val.id)) {
        val.isDelete = 1;
        this.delInvoiceList.push(val);
      }
    },
    // 上传识别的发票需要添加到附件
    attachmentAdd(file) {
      this.headForm.attachment.push(file);
    },
    // 引用历史表单数据
    async fillHistory(val) {
      const { id, ...rest } = val;
      const detailRes = await getSupplierDetail(id);
      if (detailRes.code === 200 && detailRes.data.newWidthdraw.id) {
        const widthdrawRes = await currentWidthdrawInfo(detailRes.data.newWidthdraw.id);
        if (widthdrawRes.code === 200) {
          this.$emit('setIsSaveCollectMoneyData', widthdrawRes.data.isSaveCollectMoneyData);
          if (widthdrawRes.data.collectMoneyData.list.length) {
            widthdrawRes.data.collectMoneyData.list.forEach(it => {
              it.actualAmount = (it.actualAmount / 100).toFixed(2);
              it.settlementAmount = (it.settlementAmount / 100).toFixed(2);
              it.withdrawAmount = (it.withdrawAmount / 100).toFixed(2);
            });
          }
          if (widthdrawRes.data.contractList && widthdrawRes.data.contractList.length) {
            widthdrawRes.data.contractList.forEach(it => {
              if (widthdrawRes.data.contractSign === 0 && it.contractSourceType === 1) {
                it.disable = true;
              }
              it.username = it.proposerName;
              it.oppCompanyData = it.oppCompany ? { name: it.oppCompany, id: it.oppCompanyId, type: it.oppCompanyType } : null;
            });
          }
          Object.keys(this.headForm).forEach(key => {
            // 这些字段不能被覆盖
            let fileKeys = ['supplierSource', 'channelId', 'channelName', 'costBelong', 'settleAmountTotal', 'settlementMethod'];
            if (this.isEdit) {
              fileKeys = fileKeys.concat(['id', 'workFlowId', 'version', 'isModifyForm', 'modifyNodeId', 'isInvite']);
            }
            if (!fileKeys.includes(key)) {
              this.$set(this.headForm, key, widthdrawRes.data[key]);
            }
          });
          this.headForm.invoiceList = [];
          const proposerUserObj = {
            id: widthdrawRes.data.proposer || this.userInfo.id,
            userName: rest.proposer || this.userInfo.userName,
            avatar: widthdrawRes.data.proposerAvatar || this.userInfo.avatar
          };
          this.$set(this.headForm, 'proposerUserObj', proposerUserObj);
          this.$set(this.headForm, 'proposer', widthdrawRes.data.proposer || this.userInfo.id);
          this.$set(this.headForm, 'proposerName', rest.proposer || this.userInfo.userName);
          if (!this.isEdit) {
            const deleteKeys = ['workFlowId', 'id', 'version', 'isInvite'];
            deleteKeys.forEach(key => {
              delete this.headForm[key];
            });
          }
          if (!this.headForm.contractList) this.headForm.contractList = [];
          this.$refs.collectMonenyListRef.initData();
        }
      }

      if (this.$refs.collectAccountComponentRef) {
        this.$refs.collectAccountComponentRef.clearValidate();
      }
      this.changeProposer();
    },
    insertSettleMount(data) {
      this.$set(this.headForm, 'settleAmountTotal', data.settleAmountTotal);
    },
    insertData(data) {
      const params = _.cloneDeep(data);
      if (params.proposer) {
        params.proposerUserObj = {
          id: params.proposer,
          userName: params.proposerName,
          avatar: params.proposerAvatar
        };
      } else {
        params.proposerUserObj = '';
      }
      params.invoiceList = params.invoiceList || [{}];

      params.allocationList = params.allocationList || [{}];
      if (!params.collectMoneyData.list || params.collectMoneyData.list.length === 0) {
        params.collectMoneyData.list = [
          { collectMoneyType: 0, priceRate: this.priceRate,
            _disabledObj: { actualAmount: true, withdrawAmount: true }
          }
        ];
      }
      // 当选择付款类型为全款，禁用达人到手金额和实付金额
      params.collectMoneyData.list.forEach(item => {
        if (item.collectMoneyType === 0) { // 付款类型为全款
          this.$set(item, '_disabledObj', { actualAmount: true });
          if (params.accountType === 1) {
            this.$set(item._disabledObj, 'withdrawAmount', true);
          }
        } else {
          item._disabledObj = {};
        }
      });
      params.isAllocation = params.isAllocation || 0;
      if (!params.requestFundsType && params.requestFundsType !== 0) {
        params.requestFundsType = (this.costBelong === 0 || this.costBelong === 5) ? 0 : 1;
      }
      if (params.contractNum) {
        this.isCustomContract = true;
      } else if (params.contractList && params.contractList.length > 0) {
        this.isCustomContract = false;
      }
      Array.isArray(params.contractList) && params.contractList.forEach(it => {
        it.oppCompanyData = it.oppCompany ? { name: it.oppCompany, id: it.oppCompanyId, type: it.oppCompanyType } : null;
      });
      this.headForm = params;

      const deleteKeys = ['workFlowId', 'id', 'version', 'isInvite', 'aduitInfo'];
      deleteKeys.forEach(key => {
        delete this.headForm[key];
      });
      if (this.isEdit) { // 修改时需要保留原有流程
        const { id, workFlowId, version, isModifyForm, modifyNodeId } = data;
        this.headForm.id = id;
        this.headForm.workFlowId = workFlowId;
        this.headForm.version = version;
        this.headForm.isModifyForm = isModifyForm;
        this.headForm.modifyNodeId = modifyNodeId;
      }
      this.changeProposer();
    },
    // 获取供应商详情
    getSupplierInfo() { // 从供应商管理页面进入跳转获取供应商信息
      if (!this.supplierId) return;
      supplierInfo(this.supplierId, { costBelong: this.costBelong }).then(res => {
        if (res.code === 200) {
          this.headForm.channelId = Number(this.supplierId);
          this.headForm.channelName = res.data.supplier;
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
      });
    },
    openHistoryDrawer() {
      this.$emit('openHistoryDrawer');
    },
    numberInputChange() {
      if (this.headForm.settleAmountTotal) {
        this.headForm.settleAmountTotal = Number(this.headForm.settleAmountTotal).toFixed(2);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.with-draw-form {
  .width240 {
    width: 240px;
    & ::v-deep {
      .el-input__inner {
        width: 240px;
      }
    }
  }
  .legal-input{
    & ::v-deep {
      .el-input__inner {
        padding-right: 60px;
      }
    }
  }
  &::v-deep {
    .el-form-item__label {
      padding-right: 12px !important;
    }
  }
  ::v-deep .el-form-item {
    .el-form-item__content {
      .el-radio__label {
        font-size: 14px;
      }
    }
  }
}
.switch-contract {
  font-size: 12px;
  cursor: pointer;
  color: #406eff;
  display: flex;
  align-items: center;
  padding-left: 8px;
}
.select-contract {
  display: flex;
  border: 1px solid #DCDFE6;
  width: 240px;
  padding: 0 4px 0 8px;
  border-radius: 4px;
  height: 32px;
  .select-contract-main {
    display: flex;
    flex: 1;
    overflow: hidden;
    align-items: center;
    padding-right: 8px;
    cursor: pointer;
  }
  .contract-tag {
    margin-right: 3px;
    transition: none;
  }
  .select-contract-placeholder {
    color: #c5c5c5;
    font-size: 14px;
    height: 100%;
    display: flex;
    align-items: center;
  }
}
.pay-application-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .btn-hover {
    color: #406EFF;
    background-color: #fff;
    margin-left: 5px;
    &:hover {
      background-color: #406EFF !important;
      color: #fff !important;
    }
  }
}

.title-tip {
  color: var(--color-danger);
  font-size: 14px;
}
.pay-application-tab-list {
  display: flex;
  border-bottom: 1px solid #ddd;
  margin-bottom: 16px;
  .tab-item {
    font-size: 16px;
    cursor: pointer;
    margin-right: 8px;
    line-height: 32px;
    text-align: center;
    width: 140px;
    height: 32px;
    background: #f7f8fa;
    border: 1px solid #dddddd;
    border-radius: 4px 4px 0px 0px;
    border-bottom: none;
    margin-bottom: -1px;
    z-index: 2;
    border-bottom: 1px solid #ddd;
    &.active {
      background-color: #fff;
      color: #406eff;
      font-weight: bold;
      border-bottom: 1px solid #fff;
    }
  }
}
</style>
